package com.dboper.search.relation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.dboper.search.util.MapUtil.*;

import com.dboper.search.Bootstrap;
import com.dboper.search.config.TableRelationSqlTableConfig;
import com.dboper.search.sqlparams.util.StringUtils;

public class TablesRelationDBService implements TablesRelationService,Bootstrap{
	
	private final Logger logger = LoggerFactory.getLogger(TablesRelationDBService.class);

	private TableRelationSqlTableConfig config;
	
	public TablesRelationDBService(TableRelationSqlTableConfig config) {
		this.config=config;
	}
	
	/**
	 * 需要检测数据库中是否存在table_relation表，不存在则创建
	 */
	@Override
	public void init() {
		StringBuilder sb=new StringBuilder();
		String createTableRelationSql=config.getCreateTableRelationSql();
		if(StringUtils.isNotEmpty(createTableRelationSql)){
			sb.append(createTableRelationSql);
			logger.debug("使用用户定制的sql来创建表：{}",createTableRelationSql);
		}else{
			sb.append("CREATE TABLE if not exists ");
			sb.append(config.getTableRelationTableName());
			sb.append("( `id` int(11) NOT NULL AUTO_INCREMENT,");
			sb.append("`tables_str` varchar(300) DEFAULT '',");
			sb.append("`relation` varchar(1000) DEFAULT '',");
			sb.append("`target` varchar(45) DEFAULT '',");
			sb.append("PRIMARY KEY (`id`)");
			sb.append(") ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8;");
			logger.debug("使用内置的sql来创建表：{}",sb.toString());
		}
		config.getJdbcTemplate().execute(sb.toString());
	}
	
	@Override
	public String getTablesRelation(String tablesStr) {
		return getTablesRelation(tablesStr,null);
	}
	
	@Override
	public String getTablesRelation(String tablesStr, String target) {
		String str="";
		String sql="select relation from "+config.getTableRelationTableName()+" where tables_str='"+tablesStr+"'";
		if(target!=null){
			sql+=" and target='"+target+"'";
		}
		List<Map<String,Object>> list=config.getJdbcTemplate().queryForList(sql);
		if(list!=null && list.size()>=1){
			str=(String)list.get(0).get("relation");
		}
		return str;
	}

	public void insert(String tablesStr, String relation,String target) {
		String sql="insert into "+config.getTableRelationTableName()+" (tables_str,relation,target) values('"+tablesStr+"','"+relation+"','"+target+"')";
		config.getJdbcTemplate().execute(sql);
	}
	
	/**
	 * 以tables_str作为key,这个key可以对应数据库中多条记录
	 * @return
	 */
	public Map<String,List<Map<String,Object>>> selectAll(){
		List<Map<String,Object>> ret=config.getJdbcTemplate().queryForList("select tables_str,relation,target from  "+config.getTableRelationTableName());
		Map<String,List<Map<String,Object>>> allTablesRelationsData=new HashMap<String,List<Map<String,Object>>>();
		for(Map<String,Object> item:ret){
			String tableStr=getString(item,"tables_str");
			List<Map<String,Object>> relations=allTablesRelationsData.get(tableStr);
			if(relations==null){
				relations=new ArrayList<Map<String,Object>>();
				allTablesRelationsData.put(tableStr,relations);
			}
			relations.add(item);
		}
		return allTablesRelationsData;
	}

}
